<template>
  <div class="tree-main-body">
    <!-- 左侧分类树 -->
    <div class="left-box">
      <TreeCategory
        :selected="categoryIds"
        type="no-cate"
        text="图片"
        @update="handleCategoryUpdate"
      />
    </div>

    <!-- 右侧图片展示 -->
    <div class="right-box">
      <div class="d-flex playedu-main-title float-left mb-24">
        图片 | {{ selLabel }}
      </div>

      <a-row gutter="16" style="margin-bottom: 24px">
        <a-col :span="24">
          <div class="j-b-flex">
            <div class="d-flex">
              <UploadImageSub
                :categoryIds="categoryIds"
                @update="resetImageList"
              />
              <a-button v-if="selectKey.length > 0" class="ml-16" @click="cancelAll">取消操作</a-button>
              <a-button v-else class="ml-16" @click="selectAll">批量操作</a-button>
              <a-button
                v-if="imageList.length !== 0"
                class="ml-16"
                type="primary"
                :disabled="selectKey.length === 0"
                @click="removeResource"
              >
                删除
              </a-button>
            </div>
          </div>
        </a-col>
      </a-row>

      <!-- loading -->
      <div v-if="loading" class="float-left d-j-flex mt-24">
        <a-spin size="large" />
      </div>

      <!-- empty -->
      <div v-if="!loading && imageList.length === 0" class="d-flex">
        <a-col :span="24">
          <a-empty description="暂无图片" />
        </a-col>
      </div>

      <!-- 图片列表 -->
      <div class="images-box">
        <div
          v-for="(item, index) in imageList"
          :key="item.id"
          class="imageItem"
          :style="{ backgroundImage: `url(${resourceUrl[item.id]})` }"
          @click="showImage(index, true)"
          @mouseover="showHover(index, true)"
          @mouseout="showHover(index, false)"
        >
          <i
            v-if="hoverArr[index]"
            class="checkbox"
            @click.stop.prevent="onChange(item.id)"
          ></i>
          <i
            v-if="selectKey.includes(item.id)"
            class="checked"
            @click.stop.prevent="onChange(item.id)"
          >
            <CheckOutlined />
          </i>
          <a-image
            width="200"
            style="display: none"
            :src="resourceUrl[item.id]"
            :preview="{ visible: visibleArr[index], src: resourceUrl[item.id], onVisibleChange: val => showImage(index, val) }"
          />
        </div>
      </div>

      <!-- 分页 -->
      <a-col v-if="imageList.length > 0" :span="24" style="display: flex; flex-direction: row-reverse">
        <a-pagination
          :current="page"
          :pageSize="size"
          :total="total"
          @change="handlePageChange"
          :showSizeChanger="true"
        />
      </a-col>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, h } from "vue";
import { useRoute } from "vue-router";
import { Modal, message } from "ant-design-vue";
import {  CheckOutlined, ExclamationCircleFilled } from "@ant-design/icons-vue";
import { resource } from "@/api";
import TreeCategory from "@/components/Common/tree-category.vue";
import UploadImageSub from "@/components/Common/upload-image-sub.vue";

interface ImageItem {
  id: number;
  category_id: number;
  name: string;
  extension: string;
  size: number;
  disk: string;
  file_id: string;
  path: string;
  url: string;
  created_at: string;
}

// 状态
const route = useRoute();
const imageList = ref<ImageItem[]>([]);
const resourceUrl = ref<Record<number, string>>({});
const page = ref(1);
const size = ref(32);
const total = ref(0);
const categoryIds = ref<number[]>([]);
const selectKey = ref<number[]>([]);
const visibleArr = ref<boolean[]>([]);
const hoverArr = ref<boolean[]>([]);
const selLabel = ref(route.query.label ? String(route.query.label) : "全部图片");
const loading = ref(false);
const refresh = ref(false);
const cateId = ref(Number(route.query.cid) || 0);

// 获取 URL 初始分类
onMounted(() => {
  if (cateId.value) {
    categoryIds.value = [cateId.value];
  }
  getImageList();
});

// 监听分页和刷新变化
watch([categoryIds, page, size, refresh], () => {
  getImageList();
});

// 获取图片列表
const getImageList = () => {
  loading.value = true;
  const categoryStr = categoryIds.value.join(",");
  resource
    .resourceList(page.value, size.value, "", "", "", "IMAGE", categoryStr)
    .then((res: any) => {
      total.value = res.data.result.total;
      imageList.value = res.data.result.data;
      resourceUrl.value = res.data.resource_url;

      const arr = imageList.value.map(() => false);
      visibleArr.value = [...arr];
      hoverArr.value = [...arr];
      loading.value = false;
    })
    .catch((err: any) => {
      console.log(err);
      loading.value = false;
    });
};

// 选择 / 取消选择
const onChange = (id: number) => {
  const arr = [...selectKey.value];
  const idx = arr.indexOf(id);
  if (idx === -1) arr.push(id);
  else arr.splice(idx, 1);
  selectKey.value = arr;
};

// 全选 / 取消全选
const selectAll = () => {
  selectKey.value = imageList.value.map((item) => item.id);
};
const cancelAll = () => {
  selectKey.value = [];
};

const removeResource = () => {
  if (!selectKey.value.length) return;

  Modal.confirm({
    title: "操作确认",
    icon: h(ExclamationCircleFilled),
    content: "确认删除选中图片？",
    centered: true,
    okText: "确认",
    cancelText: "取消",
    onOk() {
      resource.destroyResourceMulti(selectKey.value).then(() => {
        message.success("删除成功");
        resetImageList();
      });
    },
  });
};

// 重置列表
const resetImageList = () => {
  page.value = 1;
  imageList.value = [];
  selectKey.value = [];
  refresh.value = !refresh.value;
};

// 图片预览和 hover
const showImage = (index: number, val: boolean) => {
  visibleArr.value[index] = val;
};
const showHover = (index: number, val: boolean) => {
  hoverArr.value.fill(false);
  hoverArr.value[index] = val;
};

// 分页改变
const handlePageChange = (currentPage: number, currentSize: number) => {
  page.value = currentPage;
  size.value = currentSize;
};

// 分类树更新
const handleCategoryUpdate = (keys: number[], title: any) => {
  page.value = 1;
  categoryIds.value = keys;
  if (typeof title === "string") selLabel.value = title;
  else selLabel.value = title.props.children[0];
};
</script>

<style lang="less" scoped>
.tree-main-body {
  display: flex;
}
.left-box {
  width: 240px;
}
.right-box {
  flex: 1;
}
.images-box {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}
.imageItem {
  width: 200px;
  height: 200px;
  background-size: cover;
  background-position: center;
  position: relative;
  cursor: pointer;
}
.checkbox,
.checked {
  position: absolute;
  top: 8px;
  right: 8px;
  font-size: 16px;
  cursor: pointer;
}
</style>
